package com.zhouyu;

import com.zhouyu.service.UserService;
import org.aopalliance.aop.Advice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.Pointcut;
import org.springframework.aop.PointcutAdvisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.StaticMethodMatcherPointcut;

import java.lang.reflect.Method;

public class ProxyFactoryTest {
	public static void main(String[] args) {
		UserService userService = new UserService();
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(userService);
//		proxyFactory.setInterfaces(JdkProxyInterface.class);  //设置jdk动态代理，默认cglib
		proxyFactory.addAdvice(new MethodBeforeAdvice() {
			@Override
			public void before(Method method, Object[] args, Object target) throws Throwable {
				System.out.println("before proxyFactory");
			}
		});
		UserService proxy = (UserService) proxyFactory.getProxy();
		proxy.test();
		UserService userService1 = new UserService();
		ProxyFactory proxyFactory1 = new ProxyFactory();
		proxyFactory1.setTarget(userService1); //实际上会封装一个TargetSource
		proxyFactory1.addAdvisor(new PointcutAdvisor() {
			@Override
			public Pointcut getPointcut() {
				return new StaticMethodMatcherPointcut() {
					@Override
					public boolean matches(Method method, Class<?> targetClass) {
						return method.getName().equals("test");
					}
				};
			}

			@Override
			public Advice getAdvice() {
				return (MethodBeforeAdvice) (method, args1, target) -> {
					System.out.println("before proxyFactory");
				};
			}

			@Override
			public boolean isPerInstance() {
				return true;
			}
		});
		UserService proxy1 = (UserService) proxyFactory1.getProxy(); //proxyFactory如何判断代理方式
		proxy1.a();
	}
}
